package com.jkl.controller.login;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.jkl.entity.BaseResponse;
import com.jkl.entity.BaseResponseDTO;
import com.jkl.entity.login.vo.LoginVO;
import com.jkl.entity.login.vo.PJLog;
import com.jkl.entity.login.weight.Weight;
import com.jkl.entity.po.user.BSUser;
import com.jkl.entity.project.po.PJProjectCollect;
import com.jkl.service.user.inter.BSUserServiceInterface;
import com.jkl.untils.MD5Util;
import com.jkl.untils.VerifyCodeUtils;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/jky")
@Slf4j
public class LoginController {
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpServletResponse response;
	@Autowired
	private BSUserServiceInterface userService;



	/**
	 * @author xgs
	 * @return
	 * @description  通过row_id 获取密码
	 * @time 2021/3/6 20:12
	 */
	@PostMapping("/getPasswordState") 
	public String getPasswordState(@RequestParam(value = "rowId") String rowId) {
		return userService.getPasswordState(rowId);
	}

	/**
	 * @author xgs
	 * @return
	 * @description  修改密码
	 * @time 2021/3/3 10:41
	 */
	@PostMapping("/updatePassword")
	public int updatePassword(@RequestParam(value = "rowId") int rowId,
							  @RequestParam(value = "password") String password) {
		return userService.updatePassword(rowId, MD5Util.toMD5(password));
	}
	@PostMapping("/getLogList") // 查询日志
	public BaseResponseDTO getLogList(@RequestBody PJLog param) {
		BaseResponseDTO returnData = new BaseResponseDTO();
		PageInfo<PJLog> logList = userService.getLogList(param);
		JSONObject returnJson = new JSONObject();
		returnJson.put("logList", logList);
		returnData.setReturnData(returnJson);
		return returnData;
	}

	@PostMapping("/addLog") // 添加日志
	public void addLog(@RequestBody PJLog pjlog) {
		userService.addLog(pjlog);
	}

	@PostMapping("/login")
	public BaseResponseDTO login(@RequestBody LoginVO loginvo) {
		BaseResponseDTO returnDTO = new BaseResponseDTO();
		try {
			BSUser user = userService.findByUserName(loginvo.getUserName(), MD5Util.toMD5(loginvo.getPassWord()));
			if (user != null) {
				user.setPassword("");
				request.getSession().setAttribute("user", user);
				response.addHeader("cookieId", request.getSession().getId());
				JSONObject returnData = (JSONObject) JSON.toJSON(user);
				returnDTO.setReturnData(returnData);
			} else {
				returnDTO.setResultCode("00001").setResultMessage("账号或密码错误！");
			}

		} catch (Exception e) {
			log.error(e.toString(), e);
			returnDTO.setResultCode("10001").setResultMessage("登录失败");
		}
		return returnDTO;
	}

	@GetMapping("/logOut")
	public void logOut() {
		request.getSession().removeAttribute("user");
	}

	@RequestMapping(value = "/getImage", method = RequestMethod.GET)
	public void authImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		// 生成随机字串
		String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
		// 存入会话session
		HttpSession session = request.getSession(true);      
		// 删除以前的     
		session.removeAttribute("verCode");
		session.removeAttribute("codeTime");
		session.setAttribute("verCode", verifyCode.toLowerCase());
		session.setAttribute("codeTime", LocalDateTime.now());
		// 生成图片   
		int w = 110, h = 35;
		OutputStream out = response.getOutputStream();
		VerifyCodeUtils.outputImage(w, h, out, verifyCode);
	}

	@RequestMapping(value = "/validImage", method = RequestMethod.GET)
	public String validImage(HttpServletRequest request, HttpSession session) {
		String code = request.getParameter("code");
		Object verCode = session.getAttribute("verCode");
		if (null == verCode) {
			request.setAttribute("errmsg", "验证码已失效，请重新输入");
			return "验证码已失效，请重新输入";
		}
		String verCodeStr = verCode.toString();
		LocalDateTime localDateTime = (LocalDateTime) session.getAttribute("codeTime");
		long past = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
		long now = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
		if (verCodeStr == null || code == null || code.isEmpty() || !verCodeStr.equalsIgnoreCase(code)) {
			request.setAttribute("errmsg", "验证码错误");
			return "验证码错误";
		} else if ((now - past) / 1000 / 60 > 5) {
			request.setAttribute("errmsg", "验证码已过期，重新获取");
			return "验证码已过期，重新获取";
		} else {
			// 验证成功，删除存储的验证码
			session.removeAttribute("verCode");
			return "200";
		}
	}
	@RequestMapping(value = "/syncGarbageWeightingInfo", method = RequestMethod.POST)  
	public BaseResponse syncGarbageWeightingInfo(@RequestBody Weight[] weights) {
		BaseResponse response=new BaseResponse();
		
		if(weights!=null&&weights.length!=0) {
			try{
				for(int i=0;i<weights.length;i++) {
					userService = null;
				  userService.insertWeight(weights[i]);
				}
			  }catch(Exception e) {
				  response.setCode("0");
				  response.setMsg("server Error:500");
				  try {
				       FileWriter fw=new FileWriter("D:/project/ljptx_server/logs/lvNeng.log",true);
		               PrintWriter pw=new PrintWriter(fw);
		               pw.println("=================");
		               pw.print("operatorTime:");pw.println(("====="+new Date()+"====="));
		               pw.print("requestParam  weights:");pw.println(weights);
		               pw.print("responseParam   response:");pw.println(response);
		               pw.print("error Message:");pw.println(e);
		               pw.flush();
		               pw.close();
				    }catch(Exception ex) {
				    	ex.printStackTrace();
				    }
				  return response;
			}
			response.setCode("1");
		    response.setMsg("success");
		    return response;
		}
		else {
			response.setCode("0");
		    response.setMsg("client Error:400");
		    try {
		       FileWriter fw=new FileWriter("D:/project/ljptx_server/logs/lvNeng.log",true);
               PrintWriter pw=new PrintWriter(fw);
               pw.println("=================");
               pw.print("operatorTime:");pw.println(("====="+new Date()+"====="));
               pw.println("requestParam  weights:null");
               pw.print("responseParam   response:");pw.println(response);
               pw.flush();
               pw.close();
		    }catch(Exception e) {
		    	e.printStackTrace();
		    }
		    return response;
		    
		}
	}
	
	
}
